package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoServer {
    private ServerSocket serverSocket = null;

    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动!");
        ExecutorService service = Executors.newCachedThreadPool();
        while (true) {
            // 如果当前没有客户来连接，就会阻塞等待
            Socket clientServer = serverSocket.accept();

            //processConnect(clientServer);
//            Thread t = new Thread(() -> {
//                try {
//                    processConnect(clientServer);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            });
//            t.start();

            // 线程池
            service.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        processConnect(clientServer);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    // 通过这个方法，给当前连上的客户端提供服务
    public void processConnect(Socket clientSocket) throws IOException {
        System.out.printf("[%s:%d] 连接建立!\n", clientSocket.getInetAddress().toString(), clientSocket.getPort());
        try (InputStream inputStream = clientSocket.getInputStream()) {
            OutputStream outputStream = clientSocket.getOutputStream();
            Scanner scanner = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);

            while (true) {
                if (!scanner.hasNext()) {
                    System.out.printf("[%s:%d] 断开连接!\n", clientSocket.getInetAddress().toString(), clientSocket.getPort());
                    break;
                }
                // 1. 读取请求并解析
                String request = scanner.next();
                // 2. 根据请求计算响应
                String response = process(request);
                // 3. 把响应写回客户端
                printWriter.println(response);
                //    刷新缓冲区，避免数据没有发出去
                printWriter.flush();
                System.out.printf("[%s:%d] req: %s; rest: %s\n",
                        clientSocket.getInetAddress().toString(), clientSocket.getPort(), request,response);
            }
        }finally {
            clientSocket.close();
        }
    }

    public String process(String req) {
        return req;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server = new TcpEchoServer(8000);
        server.start();
    }
}
